package com.shioirikukuri.redis;

import com.shioirikukuri.entity.DiningTable;
import com.shioirikukuri.service.IDiningTableService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class TableAvailabilityPreloadService {

	private final IDiningTableService diningTableService;
	private final StringRedisTemplate redisTemplate;

	public TableAvailabilityPreloadService(IDiningTableService diningTableService, StringRedisTemplate redisTemplate) {
		this.diningTableService = diningTableService;
		this.redisTemplate = redisTemplate;
	}

	// 预加载 N 天的数据
	public void preloadTableData(int daysToLoad) {
		List<DiningTable> tables = diningTableService.getAllDiningTables();

		if (tables == null || tables.isEmpty()) {
			throw new RuntimeException("没有获取到任何桌位信息，无法预加载到 Redis");
		}

		for (int i = 0; i < daysToLoad; i++) {
			LocalDate date = LocalDate.now().plusDays(i);
			String dateStr = date.format(DateTimeFormatter.ISO_LOCAL_DATE);

			for (DiningTable table : tables) {
				String key = buildKey(table.getTableName(), dateStr);
				Integer availableCount = getAvailableCountForDate(table, date); // 实际从数据库读取

				redisTemplate.opsForValue().set(key, availableCount.toString());
			}
		}
	}

	// 每天执行一次，预加载第二天的数据
	public void preloadNextDayTableData() {
		LocalDate tomorrow = LocalDate.now().plusDays(1);
		String dateStr = tomorrow.format(DateTimeFormatter.ISO_LOCAL_DATE);

		List<DiningTable> tables = diningTableService.getAllDiningTables();

		if (tables == null || tables.isEmpty()) {
			throw new RuntimeException("没有获取到任何桌位信息，无法预加载到 Redis");
		}

		for (DiningTable table : tables) {
			String key = buildKey(table.getTableName(), dateStr);
			Integer availableCount = getAvailableCountForDate(table, tomorrow); // 实际从数据库读取

			redisTemplate.opsForValue().set(key, availableCount.toString());
		}
	}

	// 构建 Redis Key
	private String buildKey(String tableName, String dateStr) {
		return "table:" + tableName + ":" + dateStr;
	}

	/**
	 * 获取指定日期的可用数量
	 * @param table 桌位信息
	 * @param date  目标日期
	 * @return 可用数量
	 */
	private Integer getAvailableCountForDate(DiningTable table, LocalDate date) {
		// 假设数据库中已存储了默认每日可用数，可直接使用
		return table.getAvailableCount();
	}
}